window.onload=function(){
    cartNum()
}
//读取是否登录
var userData = $.cookie("userState");
console.log(userData)
userData = userData ? JSON.parse(userData) : null;
if (userData && userData.state === 1) {
    $(".index-login").hide();
    $(".welcome").show().children("span").text(userData.user);
} else {
    $(".index-login").show();
    $(".welcome").hide();
}
$(".welcome").children("i").click(function () {
    userData.state = 0;
    $.cookie("userState", JSON.stringify(userData));
    location.reload();
})
// 登录和注册的板块跟随滑动的js
$(window).scroll(function () {
    $(".top-wrap").animate({
        "top": document.documentElement.scrollTop
    }, 0);
    if (document.documentElement.scrollTop > 148) {
        $(".hide-search-wrap").css("display", "block")
        $(".hide-search-wrap").animate({
            "top": document.documentElement.scrollTop + 36
        }, 0)
    } else if (document.documentElement.scrollTop < 148) {
        $(".hide-search-wrap").css("display", "none")
    }
})
//二级导航显示隐藏
$(".nav-wrap").find(".main").hover(function () {
    $(".nav-wrap").find(".menu").css({
        "display": "block",
    })
}, function () {
    $(".nav-wrap").find(".menu").css({
        "display": "none",
    })
})
$(".nav-wrap").find("figure").hover(function () {
    $(this).css({
        "border": "1px solid #DAD8D9",
        "border-right": "none",
    })
    $(this).find("aside").css({
        "display": "block",
    })
}, function () {
    $(this).css({
        "border": "none",
    })

    $(this).find("aside").css({
        "display": "none",
    })
})
//放大镜
class BigImg {
    constructor() {
        // 1. 选择元素
        this.sBox = $(".s_box")[0];
        this.span = $(".s_box span")[0];
        this.bBox = $(".b_box")[0];
        this.bImg = $(".b_box img")[0];
        this.sBw = this.sBox.offsetWidth;
        this.sBh = this.sBox.offsetHeight;
        // 2. 绑定事件
        this.addEvent();
    }
    addEvent() {
        var that = this;
        // 进入事件
        this.sBox.onmouseover = function () {
            // 显示对应元素
            that.span.style.display = "block";
            that.bBox.style.display = "block";
            // 元素显示之后，才能使用js获取元素的尺寸
            // 3. 完善布局
            that.init();
        }
        // 离开事件
        this.sBox.onmouseout = function () {
            // 隐藏对应元素
            that.span.style.display = "none";
            that.bBox.style.display = "none";
        }
        // 移动事件
        this.sBox.onmousemove = function (eve) {
            var e = eve || window.event;
            // 4. 跟随鼠标移动
            that.move(e)
        }
    }
    move(e) {

        // 计算鼠标移动的距离
        // 事件目标：触发事件的元素
        var l = e.offsetX - this.span.offsetWidth / 2;
        var t = e.offsetY - this.span.offsetHeight / 2

        // 边界限定
        if (l < 0) l = 0;
        if (t < 0) t = 0;
        if (l > this.sBw - this.span.offsetWidth) l = this.sBw - this.span.offsetWidth;
        if (t > this.sBh - this.span.offsetHeight) t = this.sBh - this.span.offsetHeight;

        // 设置span的位置
        this.span.style.left = l + "px";
        this.span.style.top = t + "px";

        // 计算左边span移动的比例
        let x = l / (this.sBw - this.span.offsetWidth)
        let y = t / (this.sBh - this.span.offsetHeight)
        // console.log(x,y)

        // 根据比例计算，右侧大图要移动的距离
        this.bImg.style.left = -(this.bImg.offsetWidth - this.bBox.offsetWidth) * x + "px";
        this.bImg.style.top = -(this.bImg.offsetHeight - this.bBox.offsetHeight) * y + "px";
    }
    init() {
        let biW = this.bImg.offsetWidth / this.bBox.offsetWidth;
        let biH = this.bImg.offsetHeight / this.bBox.offsetHeight;
        this.span.style.width = this.sBw / biW + "px";
        this.span.style.height = this.sBh / biH + "px";
    }
}


$(".jieshao>ul").find("li").click(function () {
    $(this).addClass("active1").siblings().removeClass("active1").parent().next("div").children().eq($(this).index()).addClass("active2").siblings().removeClass("active2")
})


$.ajax({
    url: "http://localhost:3000/api",
    data: {
        type: "goods",
    },
    success: function (res) {
        res = JSON.parse(res)[3];
        let i;
        res.some((element, index) => {
            i = index;
            return element.id == location.search.split("=")[1];

        });
        $(".imgleft").html(`<div class="s_box">
        <img src="${res[i].图片地址}" alt="">
        <span></span>
        <p></p>
        <img src="images/pro_mj.png" alt="">
        </div>
        <a href="shouchang.html"></a>
        <div class="b_box">
            <img src="${res[i].图片地址}" alt="">
        </div>`);
        $(".wordright").html(
            `            <h3>${res[i].书名}</h3>
            <p>企业采购书卡&书目服务电话（微信同号）178-8231-4046（法定工作日9：00-17：00）</p>
            <p>定价：<span>${res[i].定价}</span></p>
            <p>文轩价：<span>${res[i].现价}</span><i>（${res[i].折扣}折）</i></p>
            <p>配送至：<select name="" id="">
                <option value="">北京</option>
                <option value="">上海</option>
                <option value="">深圳</option>
            </select></p>
            <p>作者：<a href="##">${res[i].作者}</a></p>
            <p>所属分类：<a href="##">图书&nbsp;&nbsp;&nbsp;<span>>&nbsp;&nbsp;文学/小说&nbsp;&nbsp;>&nbsp;&nbsp;小说&nbsp;&nbsp;>&nbsp;&nbsp;武侠小说</span></a></p>
            <aside>促销活动：
                <p>图书音像单笔满99减10元，满499减100！（65折内图书、电子书除外）</p>
                <p>老客户回馈，积分换礼券，购书更实惠</p>
                <p>大陆非新疆西藏地区满48包邮，新疆西藏运费每单20元<a href="##">详情</a></p>
            </aside>
            <p class="count">购买数量：<i>-</i><span>1</span><b>+</b>&nbsp;件</p>
            <p class="cart"><span class="iconfont icon-gouwuche"></span><i>加入购物车</i><b class="cart-tishi"><span>提示<i>×</i></span><span>商品已成功添加到购物车</span>
            <span><a href="cart.html">去购物车结算</a><i>继续购物>></i></span>
        </b>

             </p>
            <article>
                <p>服务：由文轩网直接销售和发货，并提供售后服务</p>
                <p>
                    <a href="##">正品保证</a>&nbsp;<span>|</span>&nbsp;
                    <a href="##">闪电发货</a>&nbsp;<span>|</span>&nbsp;
                    <a href="##">货到付款</a>&nbsp;<span>|</span>&nbsp;
                    <a href="##">高效退货</a>
                </p>
            </article>
            <p class="cart1"><b>${res[i].现价}</b>（${res[i].折扣}折）<a href="cart.html"><span class="iconfont icon-gouwuche"></span><i>去购物车结算</i> </a></p>
        </div>
`
        );
        $(".jieshao article").find("ul").html(
            `<li>作者：<a href="##">${res[i].作者}</a></li>
            <li>出版社：<a href="##">${res[i].出版社}</a></li>
            <li>出版时间：${res[i].出版时间}</li>
            <li>开本：32开</li>
            <li>页数：无</li>
            <li>印刷时间：2013-04-01</li>
            <li>字数：无</li>
            <li>装帧：盒装</li>
            <li>语种：中文</li>
            <li>版次：2</li>
            <li>印次：3</li>
            <li>版本号：21312312</li>`
        );
        new BigImg;
        // 购买数量的增加和减少
        let number = parseInt($(".wordright").find(".count").children("span").html());
        $(".wordright").find(".count").on("click", "i", function () {
            number--;
            if (number < 2) {
                number = 1;
            }
            $(".wordright").find(".count").children("span").html(number);
        });
        $(".wordright").find(".count").on("click", "b", function () {
            number++;
            $(".wordright").find(".count").children("span").html(number);
        });
        // 详情中点击购买后存入cookie并与列表中添加进去的商品对比
        $(".wordright").find(".cart").on("click", function () {
            var goodmsg = $.cookie("goodMsg");
            goodmsg = goodmsg ? JSON.parse(goodmsg) : [];
            let f;
            var res0=goodmsg.some((element, index) => {
                f = index;
                return element.id == location.search.split("=")[1];
            });
            if (res0) {
                goodmsg[f].num = parseInt(goodmsg[f].num) + number;
            } else {
                goodmsg.push({
                    id: location.search.split("=")[1],
                    num: number,
                })
            };
            $.cookie("goodMsg",JSON.stringify(goodmsg));
            cartNum();

            $(this).children("b").css({
                "display": "block",
            })
        });
        // 点击加入购物车出现弹框后消除弹窗的事件
        $(".wordright").find(".cart-tishi").on("click", "i", function () {
            $(this).parent().parent().css({
                "display": "none",
            });
            return false;
        });

    }
})

function cartNum(){
    var Num=0;
    JSON.parse($.cookie("goodMsg")).forEach(element => {
        console.log(element.num)
        Num+=element.num;
    });
    $(".search-wrap-wrap .cart").find("i").html(Num);

}
